/* eslint-disable consistent-return */
import React, { Component } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, Input, Upload, Button, message } from 'antd';
import Customer from '../../components/Customer';
import Supplier from '../../components/Supplier';
import Area from '../../components/Area';
import TableForm from './TableForm';
import { isRepeat } from '@/utils/utils';

const FormItem = Form.Item;

class AddEditModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      uploadUrl: '/nsApi/fileServer/uploadFile',
      downloadUrl: '/nsApi/fileServer/downloadFile',
      affixList: props.dataInfo.fileListFormat || [],
    };
  }

  // 获取供应商名称
  getSuppName = value => {
    const { getSuppName } = this.props;
    getSuppName(value);
  };

  // 获取地区
  getAreaList = value => {
    const areaList = [];
    const { getAreaList } = this.props;
    value.forEach(item => {
      areaList.push(item.key);
    });
    getAreaList(areaList);
  };

  // 文件限制大小
  beforeUpload = () => {};

  // 文件上传
  changeUpload = info => {
    const { file, fileList } = info;
    const { downloadUrl, affixList } = this.state;
    const newData = affixList.map(item => ({ ...item }));
    if (file.status === 'done' && file.response.success) {
      const fileId = file.response.data.split('|')[0];
      const fileName = file.response.data.split('|')[1];
      fileList.forEach(f => {
        const temp = f;
        if (String(f.uid) === String(file.uid)) {
          temp.url = `${downloadUrl}?fileId=${fileId}&fileName=${fileName}`;
          temp.linkProps = { download: `${fileName}` };
        }
      });
      newData.push({
        uid: file.uid,
        fileId,
        fileName,
      });
      this.setState({ affixList: newData });
      message.success('文件上传成功！');
    } else {
      return fileList;
    }
    if (file.status === 'error') {
      message.error('上传失败！');
    }
  };

  // 提交数据
  submitData = () => {
    const { form, productList, submitData } = this.props;
    const { affixList } = this.state;
    form.validateFields((err, values) => {
      const tempValues = values;
      if (!err) {
        const areaList = [];
        if (isRepeat(values.detList, 'pdId')) {
          message.warning('所选产品重复，请重新选择！');
          return;
        }
        affixList.forEach(item => {
          const temp = item;
          if (temp.name) {
            temp.fileId = temp.fileId || temp.uid;
            temp.fileName = temp.fileName || temp.name;
            delete temp.url;
            delete temp.name;
            delete temp.linkProps;
          }
          delete temp.uid;
        });
        values.areaList.forEach(item => {
          areaList.push({
            areaId: item.key,
            areaName: item.label,
          });
        });
        values.detList.forEach(item => {
          const temp = item;
          productList.forEach(p => {
            if (String(item.pdId) === String(p.pdId)) {
              temp.chargFre = p.billFreq;
            }
          });
        });
        tempValues.areaList = areaList;
        tempValues.affixList = affixList;
        submitData(tempValues);
      }
    });
  };

  render() {
    const {
      modalVisible,
      handleModalVisible,
      dataInfo,
      productList,
      form: { getFieldDecorator },
      confirmLoading,
      form,
    } = this.props;
    const { uploadUrl, affixList } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    // 下拉列表
    // 文件上传部分
    const uploadProps = {
      beforeUpload: info => this.beforeUpload(info),
      action: uploadUrl,
      onChange: info => this.changeUpload(info, affixList),
    };
    // 文件列表格式化
    const uploadFileFormat = e => {
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    };
    return (
      <div>
        <Modal
          width={700}
          title={dataInfo.suppProtName ? '修改' : '添加'}
          visible={modalVisible}
          okText="确定"
          cancelText="取消"
          onOk={this.submitData}
          onCancel={() => handleModalVisible(false)}
          destroyOnClose
          confirmLoading={confirmLoading}
        >
          <Form layout="horizontal">
            <FormItem {...formItemLayout} label="协议名称">
              {getFieldDecorator('suppProtName', {
                rules: [{ required: true, message: '请输入不超过100字符' }],
                initialValue: dataInfo.suppProtName || undefined,
              })(<Input placeholder="请输入" maxLength={100} />)}
            </FormItem>
            <FormItem {...formItemLayout} label="客户名称">
              {getFieldDecorator('custId', {
                initialValue: dataInfo.custId || undefined,
              })(<Customer />)}
            </FormItem>
            <FormItem {...formItemLayout} label="供应商">
              {getFieldDecorator('recvSuppId', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: dataInfo.recvSuppId || undefined,
              })(
                <Supplier
                  allowClear
                  params={{ status: 2 }}
                  onChange={this.getSuppName}
                  disabled={!!dataInfo.recvSuppId}
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="执行地区">
              {getFieldDecorator('areaList', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: dataInfo.areaListFormat || undefined,
              })(<Area mode="multiple" onChange={this.getAreaList} labelInValue />)}
            </FormItem>
            <FormItem {...formItemLayout} label="附件">
              {getFieldDecorator('affixList', {
                rules: [{ required: false, message: '请上传附件' }],
                valuePropName: 'fileList',
                getValueFromEvent: uploadFileFormat,
                initialValue: dataInfo.fileListFormat || undefined,
              })(
                <Upload {...uploadProps} beforeUpload={this.beforeUpload}>
                  <Button icon={<UploadOutlined />}>上传附件</Button>
                </Upload>
              )}
            </FormItem>
            <TableForm form={form} productList={productList} detList={dataInfo.detList || []} />
          </Form>
        </Modal>
      </div>
    );
  }
}

export default Form.create()(AddEditModal);
